﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ObserverPattern
{
    class Program
    {
        public static List<car> cars = null;
        static void Main(string[] args)
        {
            car car1 = new car();
            car1.name = "轿车";

            car car2 = new car();
            car2.name = "卡车";

            car car3 = new car();
            car3.name = "救护车";

            cars = new List<car>()
            {
                car1,car2,car3
            };

            light light = new light();

            light.ColorChanged += Light_ColorChanged;
            //light.ColorChanged += render =>
            //{
            //    if (light.color == "red")
            //    {
            //        foreach (var a in cars)
            //        {
            //            a.Stop();
            //        }
            //    }

            //    if (light.color == "green")
            //    {
            //        foreach (var a in cars)
            //        {
            //            a.Go();
            //        }
            //    }
            //};


            while (true)
            {
                light.ChangeColor();
                Thread.Sleep(5000);
            }
        }

        private static void Light_ColorChanged(light light)
        {
            if (light.color == "red")
            {
                foreach (var a in cars)
                {
                    a.Stop();
                }
            }

            if (light.color == "green")
            {
                foreach (var a in cars)
                {
                    a.Go();
                }
            }
        }
    }



    delegate void LightChangeColor(light light);

    class light
    {
        public event LightChangeColor ColorChanged;

        public string color { get; set; }

        public string status { get; set; }


        public void ChangeColor()
        {
            switch (color)
            {
                case "red":
                    color = "green";
                    break;
                case "green":
                    color = "red";
                    break;
                default:
                    color = "red";
                    break;
            }

            if (ColorChanged != null)
            {
                this.ColorChanged(this);
            }
        }

    }


    class car
    {
        public string name { get; set; }

        public string status { get; set; }

        public void Stop()
        {
            Console.WriteLine("stop");
            status = "stop";
        }

        public void Go()
        {
            Console.WriteLine("gogo");
            status = "go";
        }

        void ShowStatus()
        {
            Console.WriteLine($"{name},status:{status}");
        }
    }

}
